package com.fattiger.framework.sessionshare.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fattiger.framework.sessionshare.session.Session;
import com.fattiger.framework.sessionshare.session.SessionManager;
import com.fattiger.framework.sessionshare.session.redis.RedisSessionManager;
import com.fattiger.framework.util.StringUtils;

public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = -6987123301521005939L;
	private SessionManager manager = new RedisSessionManager();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userName = req.getParameter("username");
        String password = req.getParameter("password");
        if(StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)){
            resp.sendRedirect("/sessionshare-web");
        }
        Session session = manager.getSession(req, true);
        session.setAttribute("userName",userName);
        Cookie cookie = new Cookie(SessionManager.SESSION_COOKIE_KEY,session.getSessionId());
        cookie.setHttpOnly(true);
        resp.addCookie(cookie);
        if(!resp.isCommitted()){
	        resp.sendRedirect("./loginStatus");
	        return;
        }
    }
}
